<?php
/**
 * Created by PhpStorm.
 * User: netstan
 * Date: 14-7-14
 * Time: 下午3:40
 * 取模分布式，应对服务器相对固定情况
 */

/**
 * hash 函数
 * $key
 */
function base_Hash($key){

    $str = substr(md5($key),0,8);
    $prime = 31;
    $hash = 5381;

    for($i = 0; $i < 8; $i++ ) {
       $hash = $hash * $prime + ord($str{$i});
       ++$i;
    }

    return $hash & 0x7fffffff;
}


/**
 *  test
 */
$servers = array(
    array('host' => '192.168.1.100', 'port'=>'1211'),
    array('host' => '192.168.1.101', 'port'=>'1212'),
    array('host' => '192.168.1.102', 'port'=>'1212'),
    array('host' => '192.168.1.103', 'port'=>'1212'),
    array('host' => '192.168.1.104', 'port'=>'1212'),
    array('host' => '192.168.1.106', 'port'=>'1212')
);

$size = count($servers);
$keys = array('netstan','https','nginx','phpstrom','phpng','hhvm','mysql');
for ($i=0; $i<$size;$i++){
    $key = $keys[$i];
    $val = rand(99,999);

    $server = $servers[(base_Hash($key) % $size)];
    var_dump($server);
}





//$redis = new Redis($server['host'],$server['port']);
$mem  = new Memcached($server);


//$result = $redis->get($key,$val);
//$result = $redis->set($key,$val);

$mem->get($key);   //Get
$mem->set($key,$val);


/*
 * 分布式一致性Hash算法
 */
class FlexiHash{
    //服务器列表
    private $server_list  = array();

    //记录是否已排序
    private $isSorted = FALSE;

    //添加一台服务器



}
